import os
import base64
import mimetypes
from openai import OpenAI

from py_files.get_file_type_prompt import get_prompt_by_type

# 读取本地图片并转换为 Base64
def image_to_base64(file_path):
    with open(file_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

def image_to_data_url(file_path):
    # 获取文件的 MIME 类型（根据扩展名）
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith('image/'):
        raise ValueError("Unsupported image format")

    # 读取文件并编码为 Base64
    with open(file_path, "rb") as image_file:
        base64_data = base64.b64encode(image_file.read()).decode("utf-8")

    return f"data:{mime_type};base64,{base64_data}"

# 使用示例


# 替换为你的本地图片路径
local_image_path = "input_files/测试发票-灵算-专票.png"
# base64_image = image_to_base64(local_image_path)
data_url = image_to_data_url(local_image_path)  # 自动识别为 image/png

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
prompt=get_prompt_by_type("通用json")
completion = client.chat.completions.create(
    model="qwen-vl-plus-2025-01-25",
    messages=[
        # 系统提示词（设定角色和任务）
        {
            "role": "system",
            "content": prompt
        },
        # 用户输入（图片+问题）
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "请描述这张图片"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": data_url
                    },
                },
            ],
        }
    ],
)

print(completion.model_dump_json())